package com.freewater.javabase.demo.crypto;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class DigestDemo {

    public static void main(String[] args) {
        md5Digest();
        sha256Digest();
        ripeMD160Digest();
    }

    private static void md5Digest() {
        final MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("没有找到MD5算法实现");
            return;
        }
        digest.update("Hello".getBytes(StandardCharsets.UTF_8));
        digest.update("World".getBytes(StandardCharsets.UTF_8));
        final byte[] digestBytes = digest.digest();
        System.out.println(new BigInteger(1, digestBytes).toString(16)); // 68e109f0f40ca72a15e05cc22786f8e6
    }

    private static void sha256Digest() {
        final MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("没有找到SHA256算法实现");
            return;
        }
        digest.update("Hello".getBytes(StandardCharsets.UTF_8));
        digest.update("World".getBytes(StandardCharsets.UTF_8));
        final byte[] digestBytes = digest.digest();
        System.out.println(new BigInteger(1, digestBytes).toString(16)); // 872e4e50ce9990d8b041330c47c9ddd11bec6b503ae9386a99da8584e9bb12c4
    }

    private static void ripeMD160Digest() {
        // 注册BouncyCastle:
        Security.addProvider(new BouncyCastleProvider());
        // 按名称正常调用:
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("RipeMD160");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("没有找到RipeMD160算法实现");
        }
        md.update("HelloWorld".getBytes(StandardCharsets.UTF_8));
        byte[] result = md.digest();
        System.out.println(new BigInteger(1, result).toString(16));
    }
}
